/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-05-06
*/
package com.rzico.basics.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Company;
import com.rzico.basics.entity.CompanyEmployee;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.model.CompanyConVo;
import com.rzico.basics.model.CompanyMemberVo;
import com.rzico.basics.service.CompanyEmployeeService;
import com.rzico.basics.service.CompanyService;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.core.entity.SysOffice;
import com.rzico.core.service.SysOfficeService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.jwt.JwtTokenUtil;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业客户控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-05-06
 */
@Api(description = "企业信息接口")
@RestController
@RequestMapping("/admin/company")
public class CompanyAdminController extends BaseController {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private CompanyEmployeeService companyEmployeeService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SysOfficeService sysOfficeService;

    @Autowired
    public JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;


    /**
     * 分页查询企业客户
     *
     * @return
    */
    @ApiOperation("分页查询企业客户")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "companyCategoryId", value = "公司分类", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "企业编号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "企业名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "联系电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deleted", value = "是否删除", dataType = "Boolean", paramType = "query")
    })
    public CommResult<Company> list(String startDate, String endDate,String code, Long companyCategoryId, String name, String phone, Boolean deleted, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(startDate)){
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)){
            params.put("endDate", endDate);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }
        if (companyCategoryId != null && 0 != companyCategoryId && -1 != companyCategoryId) {
            params.put("treePath",String.valueOf(companyCategoryId) + ",");
        } else if (companyCategoryId != null) {
            params.put("companyCategoryId",String.valueOf(companyCategoryId));
        }

        if (StringUtils.isNotEmpty(code)) {
            params.put("code",code);
        }
        if (StringUtils.isNotEmpty(name)) {
            params.put("name",name);
        }

        if (StringUtils.isNotEmpty(phone)) {
            params.put("phone",phone);
        }
        if (deleted!=null) {
            params.put("deleted",deleted);
        } else {
            params.put("deleted", false);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Company> list = companyService.selectList(params);
        PageResult<Company> pageResult = new PageResult<Company>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条企业客户
     *
     * @return
    */
    @ApiOperation("查询单条企业客户")
    @GetMapping("/find/{id}")
    public CommResult<Company> find(@PathVariable String id) {
        Company result = companyService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("company",result);



        if (result.getOfficeId()!=null && !"".equals(result.getOfficeId())) {
            SysOffice sysOffice = sysOfficeService.selectByPrimaryKey(result.getOfficeId());
            if (sysOffice!=null) {
                data.put("officeName", sysOffice.getName());
            } else {
                data.put("officeName", "无");
            }
        } else {
            data.put("officeName", "无");
        }


        if (result.getMemberId()!=null) {
            Member member = memberService.selectByPrimaryKey(result.getMemberId());
            if (member!=null) {
                data.put("memberName", member.getName());
            } else {
                data.put("memberName", "无");
            }
        } else {
            data.put("memberName", "无");
        }

        return CommResult.success(data);

    }


    /**
     * 保存企业客户
     *
     * @param company
     * @return
     */
    @ApiOperation("保存企业客户")
    @PostMapping("/save")
    public CommResult<Company> save(@RequestBody Company company) {
        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            company.setEnterpriseId(enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }
        company.setDeleted(false);
        int affectCount = companyService.insertUseGeneratedKeys(company);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        Company result = companyService.findById(company.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除企业客户
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除企业客户", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除企业客户,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Company> del(@PathVariable String ids) {

        Enterprise enterprise = enterpriseService.getCurrent();
        if (null == enterprise) {
            return CommResult.error("没有开通企业");
        }
        Long enterpriseId = enterprise.getId();
        String[] allId = ids.split(",");
        for (String id : allId) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("enterpriseId", enterpriseId);
            params.put("companyId", id);
            params.put("status", 1);
            boolean result = false;
            int num = companyEmployeeService.countCompanyEmployeeNum(params);
            if (0 == num) {
                result = true;
            }
            if (!result) {
                return CommResult.error("当前公司存在在职员工，不可删除");
            }
        }
        companyService.updateDeleteById(ids.split(","));
        return CommResult.success();
    }

    /**
     * 恢复已删除的公司
     *
     * @param company
     * @return
     */
    @ApiOperation("恢复已删除的公司")
    @PostMapping("/restoreCompany")
    public CommResult<Company> restoreCompany(@RequestBody Company company){
        Company result = companyService.restoreCompany(company.getId(), company.getCompanyCategoryId());
        return CommResult.success(result);
    }

    /**
     * 更新企业客户
     *
     * @param company
     * @return
     */
    @Log(desc = "更新企业客户", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新企业客户")
    @PostMapping("/update")
    public CommResult<Company> update(@RequestBody Company company) {
        int affectCount = companyService.updateByPrimaryKeySelective(company);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Company result = companyService.findById(company.getId());
        return CommResult.success(result);
    }

    /**
     * 分页查询有推荐人的企业消费信息
     *
     * @return
     */
    @ApiOperation("分页查询有推荐人的企业消费信息")
    @GetMapping("/selectLbsList")
    @ApiImplicitParams({@ApiImplicitParam(name = "companyId", value = "公司id", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "searchMonth", value = "消费月份", dataType = "String", paramType = "query")})
    public CommResult<CompanyConVo> selectLbsList(Long companyId, String searchMonth, Pageable pageable, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        String token = request.getHeader(this.tokenHeader);
        if (StringUtils.isNotEmpty(token)){
            Map<String,String> sysUser = jwtTokenUtil.getUserInfoFromToken(token);
            Map<String, Object> memberParams = new HashMap<String, Object>();
            memberParams.put("mobile", sysUser.get("username").toString());
            List<Member> memberList = memberService.selectList(memberParams);
            if (0 < memberList.size()) {
                params.put("companyId", memberList.get(0).getCompanyId());
            }
        }
        if (null != companyId){
            params.put("companyId", companyId);
        }
        if (StringUtils.isNotEmpty(searchMonth)){
            params.put("searchMonth", searchMonth);
        }
        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<CompanyConVo> list = companyService.selectLbsList(params);
        PageResult<CompanyConVo> pageResult = new PageResult<CompanyConVo>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 统计企业消费总额
     *
     * @return
     */
    @ApiOperation("统计企业消费总额")
    @GetMapping("/selectLbsListTotalPay")
    @ApiImplicitParams({@ApiImplicitParam(name = "companyId", value = "公司id", dataType = "Long", paramType = "query") ,
            @ApiImplicitParam(name = "searchMonth", value = "消费月份", dataType = "String", paramType = "query")})
    public CommResult<CompanyConVo> selectLbsListTotalPay(Long companyId, String searchMonth, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        String token = request.getHeader(this.tokenHeader);
        if (StringUtils.isNotEmpty(token)){
            Map<String,String> sysUser = jwtTokenUtil.getUserInfoFromToken(token);
            Map<String, Object> memberParams = new HashMap<String, Object>();
            memberParams.put("mobile", sysUser.get("username").toString());
            List<Member> memberList = memberService.selectList(memberParams);
            if (0 < memberList.size()) {
                params.put("companyId", memberList.get(0).getCompanyId());
            }
        }
        if (null != companyId){
            params.put("companyId", companyId);
        }
        if (StringUtils.isNotEmpty(searchMonth)){
            params.put("searchMonth", searchMonth);
        }
        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        BigDecimal result = companyService.selectLbsListTotalPay(params);
        return CommResult.success(result);
    }


    /**
     * 查询企业与推荐人的信息
     *
     * @return
     */
    @ApiOperation("查询企业与推荐人的信息")
    @GetMapping("/selectCMList")
    @ApiImplicitParams({@ApiImplicitParam(name = "companyName", value = "公司名称", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "memberName", value = "用户名称", dataType = "String", paramType = "query")})
    public CommResult<CompanyMemberVo> selectCMList(String companyName, String memberName, Pageable pageable, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }
        String token = request.getHeader(this.tokenHeader);
        if (StringUtils.isNotEmpty(token)){
            Map<String,String> sysUser = jwtTokenUtil.getUserInfoFromToken(token);
            Map<String, Object> memberParams = new HashMap<String, Object>();
            memberParams.put("mobile", sysUser.get("username").toString());
            List<Member> memberList = memberService.selectList(memberParams);
            if (0 < memberList.size()) {
                Map<String, Object> companyEmployeeParams = new HashMap<String, Object>();
                companyEmployeeParams.put("companyId", memberList.get(0).getCompanyId());
                companyEmployeeParams.put("memberId", memberList.get(0).getId());
                List<CompanyEmployee> companyEmployeeList = companyEmployeeService.selectList(companyEmployeeParams);
                if (0 < companyEmployeeList.size()) {
                    params.put("memberName", companyEmployeeList.get(0).getEmpName());
                }
            }
        }
        if (StringUtils.isNotEmpty(companyName)){
            params.put("companyName", companyName);
        }
        if (StringUtils.isNotEmpty(memberName)){
            params.put("memberName", memberName);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<CompanyMemberVo> list = companyService.selectCMList(params);
        PageResult<CompanyMemberVo> pageResult = new PageResult<CompanyMemberVo>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

}
